<template>
  <el-card shadow="hover" class="mt-20">
    <el-button
      type="primary"
      :icon="Plus"
      :disabled="!categoryStore.category3Id"
      @click="addAttrList"
      >添加属性</el-button
    >
    <el-table :data="attrList" border class="mt-20">
      <el-table-column label="序号" width="60" type="index" align="center" />
      <el-table-column prop="attrName" label="属性名" width="150px" />
      <el-table-column label="属性值列表">
        <template v-slot="{ row }">
          <el-tag
            type="success"
            v-for="attrValue in row.attrValueList"
            :key="attrValue.id"
            class="mr-10"
          >
            {{ attrValue.valueName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="editAttList(row)"
          ></el-button>
          <el-popconfirm title="您确定要删除吗?" @confirm="delAttrList(row.id)">
            <template #reference>
              <el-button type="danger" size="small" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AttrList",
};
</script>

<script lang="ts" setup>
import { watch, ref } from "vue";
import { useCategoryStore } from "@/stores/category";
import { useAttrStore } from "@/stores/attr";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { getAttrInfoListApi, deleAttrInfoListApi } from "@/api/product/attr";
import type { AttrList, AttrItem } from "@/api/product/model/attrModel";
import { ElMessage, ElMessageBox } from "element-plus";

//删除属性
const delAttrList = async (id: number) => {
  await deleAttrInfoListApi(id);
  ElMessage.success("属性删除成功");
  getCategory();
};

//
const attrList = ref<AttrList>([]);

const attrStore = useAttrStore();
const categoryStore = useCategoryStore();

const getCategory = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrInfoListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
};

// 监视三级分类的变化
watch(
  () => categoryStore.category3Id,
  () => {
    const { category3Id } = categoryStore;
    if (!category3Id) {
      attrList.value = [];
      return;
    }
    getCategory();
  },
  {
    immediate: true,
  }
);

//接收自定义事件传递过来的函数
const emit = defineEmits(["setIsShowAttrList"]);
const addAttrList = () => {
  emit("setIsShowAttrList", false);
};

//编辑属性
const editAttList = (row: AttrItem) => {
  emit("setIsShowAttrList", false);
  attrStore.attrItem = row;
};
</script>

<style scoped></style>
